package com.keyinong.caizhengting.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.AbsoluteSizeSpan;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.LayoutParams;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.keyinong.caizhengting.R;
import com.keyinong.caizhengting.adapter.OrderViewPagerAdapter;
import com.keyinong.caizhengting.entity.GoodsTwoSortBean;
import com.keyinong.caizhengting.entity.GouwucheEntity;
import com.keyinong.caizhengting.fragment.GoodsTwoSortFragment;
import com.keyinong.caizhengting.tools.HttpTools;
import com.keyinong.caizhengting.tools.MyShowDialog;
import com.keyinong.caizhengting.tools.NetWorkUtil;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * @author：郑谦
 * @时间：2017-4-10 下午4:02:27
 * @类名：GoodsTwoSortActivity.java
 * @功能: 晚餐
 */
public class GoodsTwoSortActivity extends FragmentActivity {
    static int geshu = 0;
    static ArrayList<GouwucheEntity> infolist;
    /**
     * 商品数
     */
//	private static TextView tv_shangpin;
    private static TextView tv_tishi;


    private OrderViewPagerAdapter mVPAdapter;
    /**
     * 数量
     */
    private static TextView tv_shuliang;
    private static int shangping;
    /**
     * 合计
     */
    private static TextView tv_heji;
    public static Handler myhanler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            Bundle bu = (Bundle) msg.obj;
            String sopt = bu.getString("sopt1");
            String str = bu.getString("str1");
            int index = bu.getInt("index1");
            if (sopt.equals("jia1")) {
                tv_shuliang.setText(str);
            }
            if (sopt.equals("jian1")) {
                tv_shuliang.setText(str);
            }
            if (sopt.equals("zongjia1")) {
                tv_heji.setText(str);
            }
            if (sopt.equals("qingchu1")) {
                tv_shuliang.setText(str);
            }
            super.handleMessage(msg);
        }

    };
    private static Double heji = 0.0;
    /**
     * 屏幕宽度
     */
    int widht;
    /**
     * 水平滑动
     */
    private ScrollView hs_goodsSortTop;
    /**
     * 分类的背景
     */
    private ImageView img_goodsSort_line;
    /**
     * 商品分类
     */
    private RadioGroup rg_twosort;
    /**
     * viewpager
     */
    private ViewPager vp_sortGoods;
    /**
     * 商品二级分类的集合
     */
    private ArrayList<GoodsTwoSortBean> twolist;
    /**
     * 左侧栏列表
     */
    private ArrayList<Fragment> fragemtlist;
    /**
     * 返回
     */
    private ImageButton ib_back;
    /**
     * 结算框
     */
    private RelativeLayout rl_jiesuan;
    /**
     * 结算
     */
    private Button btn_tijiao;
    /**
     * 跳转到购物车
     */
    private ImageView iv_gouwuche;
    private OnCheckedChangeListener oncheck = new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(RadioGroup arg0, int arg1) {
//			vp_sortGoods.setCurrentItem(arg1);
            RadioButton rb = null;
            vp_sortGoods.setCurrentItem(arg1);
            for (int i = 0; i < arg0.getChildCount(); i++) {
                rb = (RadioButton) arg0.getChildAt(i);
                if (rb.isChecked()) {
                    rb.setTextColor(getResources().getColor(R.color.rg_stork_blue));
                } else {
                    rb.setTextColor(getResources().getColor(R.color.caidan));
                }
            }

        }
    };
    /**
     * viewpager的监听事件
     */
    private OnPageChangeListener onpagerchange = new OnPageChangeListener() {
        private int check = 0;

        @Override
        public void onPageSelected(int arg0) {
            RadioButton rb = (RadioButton) rg_twosort.getChildAt(arg0);
            rb.setChecked(true);

            if (arg0 > check && arg0 > 2)
//				hs_goodsSortTop.scrollBy(0, widht/4);
            {
                hs_goodsSortTop.scrollTo(0, widht / 4);
            } else if (arg0 <= check && arg0 <= 6)
//				hs_goodsSortTop.scrollBy(0,-(widht/4) );
            {
                hs_goodsSortTop.scrollTo(0, -(widht / 4));
            }
            check = arg0;

        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
            RelativeLayout.LayoutParams params = (android.widget.RelativeLayout.LayoutParams) img_goodsSort_line
                    .getLayoutParams();
            params.leftMargin = (int) (widht / 12 * (arg0 + arg1));
            img_goodsSort_line.setLayoutParams(params);
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
//			((RadioButton) rg_twosort.getChildAt(arg0)).setChecked(true);
        }
    };

    private TextView mTvTitle;
    private int mType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//			getWindow().addFlags(
//					WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.fragment_fenlei);
//		MyShowDialog.closeLoadingDialog();
        //获得屏幕宽度
        getWindowWith();
//		initRes();
//		getPix();

        mTvTitle = findViewById(R.id.tv_shouye);

        Intent intent = getIntent();
        if (null != intent) {
            mType = intent.getIntExtra("type", 0);
            if (mType != 0) {
                mTvTitle.setText("服务部");
            }
            getGoodsSort(mType);
            //getGoodsSort(intent.getIntExtra("type", 0));
        }
    }

    private void initRes() {
//		tv_shangpin=(TextView)findViewById(R.id.tv_shangpin);
        tv_shuliang = (TextView) findViewById(R.id.tv_total_num);
        tv_heji = (TextView) findViewById(R.id.tv_total_price);
        hs_goodsSortTop = (ScrollView) findViewById(R.id.hs_goodsSortTop);
        img_goodsSort_line = (ImageView) findViewById(R.id.img_goodsSort_line);
        rg_twosort = (RadioGroup) findViewById(R.id.rg_twosort);
        vp_sortGoods = (ViewPager) findViewById(R.id.vp_sortGoods);
        rl_jiesuan = (RelativeLayout) findViewById(R.id.rl_bottom);
        rl_jiesuan.bringToFront();
        iv_gouwuche = (ImageView) findViewById(R.id.iv_gouwuche);
        iv_gouwuche.bringToFront();
        iv_gouwuche.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
//				startActivityForResult(intent, requestCode);
                Intent intent = new Intent();
                intent.setClass(GoodsTwoSortActivity.this, FanqiedingcanActivity.class);
                intent.putExtra("code", "1");
                startActivity(intent);
                finish();
            }
        });
        btn_tijiao = (Button) findViewById(R.id.btn_submit);
        btn_tijiao.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(GoodsTwoSortActivity.this, FanqiedingcanActivity.class);
                intent.putExtra("code", "1");
                startActivity(intent);
                finish();
            }
        });
//		getGoodsSort();
        Gouwuche();
        vp_sortGoods.addOnPageChangeListener(onpagerchange);
        rg_twosort.setOnCheckedChangeListener(oncheck);
        ib_back = (ImageButton) findViewById(R.id.ib_back);
        ib_back.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
//				Intent intent = new Intent(getApplicationContext(), SearchActivity.class);
//				startActivity(intent);
                finish();
            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();

    }

    /**
     * 获取购物车信息
     */
    private void Gouwuche() {
        if (!NetWorkUtil.isNetwork(getApplicationContext())) {
            Toast.makeText(getApplicationContext(), "当前网络不可用", Toast.LENGTH_SHORT).show();
            return;
        }
        infolist = new ArrayList<GouwucheEntity>();
        SharedPreferences sp = getSharedPreferences("spReg", Context.MODE_PRIVATE);
        String token = sp.getString("data", "");
        HttpTools httptools = new HttpTools(getApplicationContext());
//		if (httptools == null) {
//			httptools = new HttpTools(getApplicationContext());
//		}
        httptools.getShoppingCat(token, new JsonGouwuche());
    }

    /**
     * 得到商品分类
     */
    private void getGoodsSort(int type) {
        if (!NetWorkUtil.isNetwork(getApplicationContext())) {
            Toast.makeText(getApplicationContext(), "当前网络不可用", Toast.LENGTH_SHORT).show();
            return;
        }
        twolist = new ArrayList<GoodsTwoSortBean>();
        fragemtlist = new ArrayList<Fragment>();
//		twolist.add(new GoodsTwoSortBean(0 + "", "全部"));
        SharedPreferences sp = getSharedPreferences("spReg", Context.MODE_PRIVATE);
        String token = sp.getString("data", "");

        HttpTools toolModel = new HttpTools(getApplicationContext());
        toolModel.getCategories(token, type, new JsonGetTwoSort());
    }

    /**
     * 增加左侧栏滑动按钮
     */
    private void addRadioButton() {

        // RelativeLayout.LayoutParams fp = new RelativeLayout.LayoutParams(
        // LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 1);
        // fp.width = widht / 4 * rg_twosort.getChildCount();
        // img_goodsSort_bg.setLayoutParams(fp);

        RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT, 1);
        params.height = widht / 12;
        // 居中
        params.gravity = Gravity.CENTER;
//		Log.e("info", "twolist.size()---"+twolist.size());

        for (int i = 0; i < twolist.size(); i++) {

            RadioButton rb = new RadioButton(getApplicationContext());


            rb.setId(i);
            // LinearLayout.layoutparam
            // .setWeight()
            rb.setHeight(widht / 12);
//			rb.setPadding(0, 15, 0, 15);
            rb.setGravity(Gravity.CENTER);
//		    rb.setPadding(0, 18, 0, 18);
//			rb.setWidth(LayoutParams.MATCH_PARENT);
            rb.setHeight(LayoutParams.MATCH_PARENT);
            rb.setButtonDrawable(android.R.color.transparent);
            rb.setBackground(getResources().getDrawable(R.drawable.select_dinner));
            rb.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15);
//			rb.setBackgroundResource(R.drawable.img_guige1);
//			rb.setTextColor(R.color.select_color)
            rb.setTextColor(getResources().getColor(R.color.select_color));
//			if (i == 0) {
//				rb.setTextColor(getResources().getColor(R.color.white));
//				rb.setChecked(true);
//			}

            if ("0".equals(twolist.get(i).getLim())) {
                rb.setText(twolist.get(i).getName());
            } else {
                String rbStr = twolist.get(i).getName() + "\n(限购:" + twolist.get(i).getLim() + ")";
                SpannableString textAttr = new SpannableString(rbStr);
//					textAttr.setSpan(15, 0, 2,
//							Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//					textAttr.setSpan(new TextAppearanceSpan(null,2,45,null,null), 2, rbStr.length(),
//							Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                textAttr.setSpan(new AbsoluteSizeSpan(12, true), 2,
                        rbStr.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//					textAttr.setSpan(13, 2, rbStr.length(),
//							Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                rb.setText(textAttr/*,TextView.BufferType.SPANNABLE*/);

            }
            rg_twosort.addView(rb, params);
//			getPix();

        }
        if (twolist.size() > 0) {
            ((RadioButton) rg_twosort.getChildAt(0)).setChecked(true);
        }

        for (int i = 0; i < twolist.size(); i++) {
            GoodsTwoSortFragment twosortfragment = new GoodsTwoSortFragment();
            Bundle bundle = new Bundle();
//			bundle.putString("catid", getIntent().getStringExtra("id"));
            bundle.putString("varid", twolist.get(i).getId());
            bundle.putInt("type", mType);
            twosortfragment.setArguments(bundle);
            fragemtlist.add(twosortfragment);
        }
//		FragmentManager childFragmentManager = getChildFragmentManager();
        mVPAdapter = new OrderViewPagerAdapter(getSupportFragmentManager(), fragemtlist);
        vp_sortGoods.setAdapter(mVPAdapter);
    }

    /**
     * 获得屏幕宽度
     */
    private void getWindowWith() {
        // 获取分辨率
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        // 获得屏幕宽度
        widht = dm.heightPixels;
    }

    /**
     * 设置图片的初始位置
     */
    private void getPix() {
        int imgwidth = widht / 12;
        RelativeLayout.LayoutParams params = (android.widget.RelativeLayout.LayoutParams) img_goodsSort_line
                .getLayoutParams();
        params.height = imgwidth;
        img_goodsSort_line.setLayoutParams(params);
    }

    public class JsonGouwuche extends JsonHttpResponseHandler {


        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            Log.i("zq", "分类中的购物车-------" + response.toString());
            try {
                boolean code = response.getBoolean("code");
                String msg = response.getString("msg");
                if (code) {
                    JSONObject object = response.getJSONObject("data");
                    String geshu = object.getString("amount");
                    String total = object.getString("total");
                    JSONArray array = object.getJSONArray("shoppingcarts");
                    for (int i = 0; i < array.length(); i++) {
                        JSONObject data = array.getJSONObject(i);
                        String id = data.getString("id");
                        String productid = data.getString("productid");
                        String name = data.getString("name");
                        String content = data.getString("content");
                        String price = data.getString("price");
//						String image=data.getString("image");
                        int type = data.getInt("type");
                        String shelve = data.getString("shelve");
                        String stock = data.getString("stock");
                        String perlim = data.getString("perlim");
                        String amount = data.getString("amount");
                        String buyamount = data.getString("buyamount");
                        infolist.add(new GouwucheEntity(id, productid, name, content, price, amount, shelve, stock, perlim, buyamount, type));
                    }
                    shangping = array.length();
//					tv_shangpin.setText(""+shangping);
                    tv_shuliang.setText(geshu);
//					tv_heji.setText(""+(int)(Double.parseDouble(total)*10));
                    tv_heji.setText(total);
                } else {
                    Toast.makeText(GoodsTwoSortActivity.this, msg, Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    private class JsonGetTwoSort extends JsonHttpResponseHandler {

        @Override
        public void onStart() {
            MyShowDialog.showLoadingDialog(GoodsTwoSortActivity.this, "请稍后....");
            super.onStart();
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            MyShowDialog.closeLoadingDialog();
            Log.w("TAG", response.toString());
            initRes();
            try {
                JSONArray array = response.getJSONArray("data");
                for (int i = 0; i < array.length(); i++) {
                    Log.w("TAG", array.get(i).toString());
                    JSONObject data = array.getJSONObject(i);
                    String id = data.getString("id");
                    String name = data.getString("name");
                    String lim = data.getString("lim");
                    twolist.add(new GoodsTwoSortBean(id, name, lim));
                }
                addRadioButton();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

}
